﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.FileIO;
using System.Management;
using System.IO;
using System.Diagnostics;

namespace TotalCrytography
{
    public partial class ChildWindow : UserControl
    {
        public ChildWindow oppChild = null;
        private String _curDir;
        public String CurDirectory
        {
            get { return _curDir; }
            set { _curDir = value; }
        }
        private List<String> _curSelectFiles;
        public List<String> CurSelectFile
        {
            get { return _curSelectFiles; }
            set { _curSelectFiles = value; }
        }

        public ChildWindow()
        {
            InitializeComponent();
            lstFile.SmallImageList = FileIcons.Instance.SmallImageList;
            lstFile.SmallImageList.ColorDepth = ColorDepth.Depth32Bit;
            _curSelectFiles = new List<string>();
        }

        
        public void Init(String curDir)
        {
            _curDir = curDir;
            txtPath.Text = curDir;
            string[] DriveList = Environment.GetLogicalDrives();
            cbListDist.DataSource = DriveList;
            cbListDist.Text = curDir[0].ToString() + @":\" ;
        }

        public void SetEnable(bool state)
        {
            createDigitalSignatureToolStripMenuItem.Enabled = state;
            decryptToToolStripMenuItem.Enabled = state;
        }

        public bool ShowListFile()
        {
            lstFile.Items.Clear();
            DirectoryInfo thisDirInfo = new DirectoryInfo(_curDir);
            if (_curDir != Directory.GetDirectoryRoot(_curDir))
                lstFile.Items.Add(new ListViewItem(new string[] {"...", "", "", 
                    thisDirInfo.CreationTime.ToString()}));

            foreach (DirectoryInfo dir in thisDirInfo.GetDirectories())
            {
                ListViewItem lvItem = new ListViewItem(dir.Name);
                lvItem.ImageIndex = FileIcons.Instance.GetIconIndex(dir)-1;
                lvItem.Tag = dir;
                lvItem.SubItems.Add("");
                lvItem.SubItems.Add("");
                lvItem.SubItems.Add(dir.CreationTime.ToString());
                lstFile.Items.Add(lvItem);
            }
            foreach (FileInfo file in thisDirInfo.GetFiles())
            {
                ListViewItem lvItem;
                try
                {
                    lvItem = new ListViewItem(file.Name.Remove(file.Name.Length - file.Extension.Length));
                }
                catch
                {
                    lvItem = new ListViewItem(file.Name);
                }
                lvItem.ImageIndex = FileIcons.Instance.GetIconIndex(file) - 1;
                lvItem.Tag = file;
                try
                {
                    lvItem.SubItems.Add(file.Extension.Remove(0, 1));
                }
                catch
                {
                    lvItem.SubItems.Add(file.Extension.ToString());
                }
                lvItem.SubItems.Add(file.Length.ToString());
                lvItem.SubItems.Add(file.CreationTime.ToString());
                lstFile.Items.Add(lvItem);
            }
            lstFile.Items[0].Selected = true;
            return true;
        }

        private void lstFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            _curSelectFiles.Clear();
            foreach (ListViewItem item in lstFile.SelectedItems)
            {
                //_curSelectFiles.Add(_curDir + lstFile.SelectedItems[i].Tag.ToString());
                string path = _curDir + item.SubItems[0].Text + (item.SubItems[1].Text == "" ? "" : "." + item.SubItems[1].Text);
                if (Directory.Exists(path))
                    _curSelectFiles.Add(path);
                else if (File.Exists(path))
                    _curSelectFiles.Add(path);
            }
        }

        private void lstFile_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (Directory.Exists( _curDir + lstFile.SelectedItems[0].SubItems[0].Text))
            {
                string selectFolder = this.lstFile.SelectedItems[0].SubItems[0].Text;
                if (selectFolder == "...")
                {
                    int idx = _curDir.Remove(_curDir.Length - 1).LastIndexOf('\\');
                    _curDir = _curDir.Remove(idx + 1);
                    txtPath.Text = _curDir;
                }
                else
                {
                    string newDir = _curDir + selectFolder + "\\";
                    if (Directory.Exists(newDir) == false)
                    {
                        MessageBox.Show("The directory " + newDir + "does not exist", "TotalCrytography", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        return;
                    }
                    _curDir = newDir;
                    txtPath.Text = _curDir;
                }
                try
                {
                    ShowListFile();
                }
                catch
                {
                    
                    MessageBox.Show("Can not explore this folder", "TotalCrytography", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
            else
            {
                string str = _curDir + "\\" + lstFile.SelectedItems[0].Text + "." + lstFile.SelectedItems[0].SubItems[1].Text;
                try
                {
                    Process.Start(str);
                }
                catch
                {
                    MessageBox.Show("Can not open this file", "TotalCrytography", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
        }

        private void cbListDist_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _curDir = cbListDist.Text;
                txtPath.Text = _curDir;
                ShowListFile();
            }
            catch
            {
                MessageBox.Show("Please insert disc into driver");
            }
        }

        public void CopyTo()
        {
            if (MessageBox.Show("Do you really want to continue?", "Copy To", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                if (_curDir == oppChild._curDir)
                {
                    MessageBox.Show("The source folder and destination folder are the same!", "TotalCrytography", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }

                foreach (ListViewItem item in lstFile.SelectedItems)
                {
                    string path = _curDir + item.SubItems[0].Text + (item.SubItems[1].Text == "" ? "" : "." + item.SubItems[1].Text);
                    if (Directory.Exists(path))
                        Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(path, oppChild.CurDirectory + "\\" + item.SubItems[0].Text);
                    else
                    {
                        string fileName = item.SubItems[0].Text + (item.SubItems[1].Text == "" ? "" : "." + item.SubItems[1].Text);
                        if (File.Exists(path))
                        {
                            try
                            {
                                Microsoft.VisualBasic.FileIO.FileSystem.CopyFile(path, oppChild.CurDirectory + "\\" + fileName);
                            }
                            catch (System.Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                                return;
                            }
                        }
                    }
                }
                oppChild.ShowListFile();
            }
        }

        public void MoveTo()
        {
            if (MessageBox.Show("Do you really want to move files or folders?", "Move To", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                if (_curDir == oppChild._curDir)
                {
                    MessageBox.Show("The source folder and destination folder are the same!", "TotalCrytography", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return;
                }
                foreach (ListViewItem item in lstFile.SelectedItems)
                {
                    string path = _curDir + item.SubItems[0].Text + (item.SubItems[1].Text == "" ? "" : "." + item.SubItems[1].Text);
                    if (Directory.Exists(path))
                        Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(_curDir + "\\" + item.SubItems[0].Text, oppChild._curDir + "\\" + item.SubItems[0].Text);
                    else
                    {
                        string fileName = item.SubItems[0].Text + (item.SubItems[1].Text == "" ? "" : "." + item.SubItems[1].Text);
                        if (File.Exists(path))
                        {
                            try
                            {
                                Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(_curDir + "\\" + fileName, oppChild.CurDirectory + "\\" + fileName);
                            }
                            catch (System.Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                                return;
                            }
                        }
                    }
                }
                this.ShowListFile();
                oppChild.ShowListFile();
            }
        }

        public void Delete()
        {
            if (MessageBox.Show("Do you really want to delete files or folders?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                foreach (ListViewItem item in lstFile.SelectedItems)
                {
                    string filePath = _curDir + item.SubItems[0].Text + (item.SubItems[1].Text == "" ? "" : "." + item.SubItems[1].Text);
                    if (Directory.Exists(filePath))
                        Directory.Delete(filePath);
                    else
                    {

                        if (File.Exists(filePath))
                            File.Delete(filePath);
                    }
                }
                ShowListFile();
            }
        }

        public void NewFolder()
        {
            NewFolderGUI newfolderFrm = new NewFolderGUI();
            if (newfolderFrm.ShowDialog() == DialogResult.OK)
                Directory.CreateDirectory(_curDir + newfolderFrm.GetFolderName());
            ShowListFile();
        }


        private void lstFile_KeyDown(object sender, KeyEventArgs e)
        {
            if (lstFile.SelectedItems.Count == 0 && e.KeyCode != Keys.F7)
                return;
            switch (e.KeyCode)
            {
                case Keys.Back:
                    if (lstFile.Items[0].Text == "...")
                    {
                        string dir = _curDir.Substring(0, _curDir.Length - 1);
                        int temp = dir.LastIndexOf("\\");
                        _curDir = _curDir.Remove(temp);
                        _curDir += "\\";
                        ShowListFile();
                        txtPath.Text = _curDir;
                    }
                    break;
                case Keys.Enter:
                    lstFile_MouseDoubleClick(null, null);
                    break;
                case Keys.F3:
                case Keys.F4:
                    for (int i = 0; i < CurSelectFile.Count; i++)
                    {
                        if (File.Exists(CurSelectFile[i]))
                            System.Diagnostics.Process.Start(@"Notepad2\Notepad2.exe", CurSelectFile[i]);
                    }
                    break;
                case Keys.F5:
                    CopyTo();
                    break;
                case Keys.F6:
                    MoveTo();
                    break;
                case Keys.F7:
                    NewFolder();
                    break;
                case Keys.Delete:
                case Keys.F8:
                    Delete();
                    break;
            }
        }

        private void txtPath_KeyDown(object sender, KeyEventArgs e)
        {
           if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    ShowListFile();
                    _curDir = txtPath.Text;
                }
                catch
                {
                    MessageBox.Show("Can not explore this folder", "TotalCrytography", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    txtPath.Text = _curDir;
                }
            }
        }


        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lstFile_MouseDoubleClick(sender, null);
        }

        private void encryptToToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EncryptGUI frm = new EncryptGUI(this._curSelectFiles);
            if (frm.ShowDialog() == DialogResult.OK)
                ShowListFile();
        }

        private void verifyDigitalSignatureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckGUI checkFrm = new CheckGUI(_curSelectFiles);
            checkFrm.Show();
        }

        private void decryptToToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DecryptGUI frm = new DecryptGUI(this._curSelectFiles,MainGUI.GetCurrentPass(),MainGUI.GetCurrentUser().PrivateKey);
            if (frm.ShowDialog() == DialogResult.OK)
                ShowListFile();
        }

        private void createDigitalSignatureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SignGUI signFrm = new SignGUI(_curSelectFiles);
            if(signFrm.ShowDialog() == DialogResult.OK )
                Refresh();
            
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyTo();
        }

        private void moveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MoveTo();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewFolder();
        }

        private void lstFile_MouseClick(object sender, MouseEventArgs e)
        {
            if (e != null)
                if (e.Button == MouseButtons.Right)
                {
                    if (lstFile.SelectedItems.Count > 0)
                        if (lstFile.SelectedItems[0].Text != "...")
                            contextMenuStrip1.Show(PointToScreen(e.Location));
                }
            if (lstFile.SelectedItems.Count == 0)
                lstFile.Items[0].Selected = true;
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowListFile();
        }

        private void zipToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ZipGUI zipFrm = new ZipGUI(_curSelectFiles);
            if (zipFrm.ShowDialog() == DialogResult.OK)
                ShowListFile();
        }

        private void unzipToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _curSelectFiles.Count; i++)
            {
                UnzipGUI unzipFrm = new UnzipGUI(_curSelectFiles[i]);
                unzipFrm.ShowDialog();
            }
            ShowListFile();
            
        }
        
    }
}
